import matplotlib.pyplot as plt
import load2
import random
import load

window=0.3

class commodity:
    def __init__(self):
        self.x_data = []
        self.y_data = []
        self.date = 10
        self.sum=0
        self.num=0

    def nextTime(self,newDate):
        y=-1
        if self.num!=0:
            y=self.sum/self.num
        else:
            if len(self.x_data)!=0:
                y=self.y_data[-1]

        if y!=-1:
            if len(self.x_data)==0: # 本次有值且之前没添加过
                self.date=round(newDate, 1)
                self.x_data.append(self.date)
                self.y_data.append(y)
                print(self.date)
            else:
                while newDate>self.date+window:
                    self.y_data.append(y)
                    self.x_data.append(self.date)
                    self.date += window

        self.sum=0
        self.num=0

    def add(self,n):
        self.sum+=n
        self.num+=1

allCommodity={}
for i in range(1,load2.allNum):
    id = str(load2.getCell(i, load2.id))
    allCommodity[id]=commodity()

for i in range(1,load2.allNum):
    id = str(load2.getCell(i, load2.id))
    c = allCommodity[id]
    date = float(load2.getCell(i, load2.date))
    if date > c.date + window:
        c.nextTime(date)
    star = float(load2.getCell(i, load2.star))
    r = float(load2.getCell(i,load2.r))
    c.add(star*r)

def randColor():
    return random.randint(0,5)/10

text='date,reputation\n'
for id,c in allCommodity.items():
    print(id)
    text+='\n'+id+'\n'
    for i in range(len(c.x_data)):
        text+=str(c.x_data[i])+','+str(c.y_data[i])+'\n'
load.writeFile('奶嘴声誉.csv',text)

print(len(allCommodity))
drawNum=0
for _,c in allCommodity.items():
    if len(c.x_data)!=0:
        plt.plot(c.x_data,c.y_data,color=(randColor(),randColor(),randColor()),linewidth=0.5)
        drawNum+=1
        if drawNum>50:
            break
plt.show()